#!/usr/bin/env python3
"""
仲裁案件管理和字符串加解密 MCP Server
提供字符串加解密功能和仲裁案件数据库查询功能
"""

import asyncio
import json
from typing import Any, Sequence
from mcp.server import Server
from mcp.types import (
    Resource,
    Tool,
    TextContent,
    ImageContent,
    EmbeddedResource,
    LoggingLevel
)
import mcp.server.stdio
import mcp.types as types

from database_manager import ArbitrationDB
from encryption import StringEncryption

# 初始化服务器
server = Server("arbitration-crypto-server")

# 初始化数据库和加密服务
db = ArbitrationDB()
crypto = StringEncryption()

@server.list_resources()
async def handle_list_resources() -> list[Resource]:
    """列出可用资源"""
    return [
        Resource(
            uri="database://arbitration_cases",
            name="仲裁案件数据库",
            description="包含所有仲裁案件的数据库",
            mimeType="application/json",
        ),
        Resource(
            uri="crypto://encryption_service",
            name="字符串加解密服务",
            description="提供字符串加密和解密功能",
            mimeType="text/plain",
        )
    ]

@server.read_resource()
async def handle_read_resource(uri: str) -> str:
    """读取资源内容"""
    if uri == "database://arbitration_cases":
        cases = db.query_cases()
        return json.dumps(cases, ensure_ascii=False, indent=2)
    elif uri == "crypto://encryption_service":
        return "字符串加解密服务已就绪。使用工具进行加密和解密操作。"
    else:
        raise ValueError(f"未知资源: {uri}")

@server.list_tools()
async def handle_list_tools() -> list[Tool]:
    """列出可用工具"""
    return [
        Tool(
            name="encrypt_string",
            description="加密字符串",
            inputSchema={
                "type": "object",
                "properties": {
                    "text": {"type": "string", "description": "要加密的文本"},
                    "use_password": {"type": "boolean", "description": "是否使用密码加密", "default": False},
                    "password": {"type": "string", "description": "加密密码（如果use_password为true）"}
                },
                "required": ["text"]
            },
        ),
        Tool(
            name="decrypt_string",
            description="解密字符串",
            inputSchema={
                "type": "object",
                "properties": {
                    "encrypted_text": {"type": "string", "description": "要解密的文本"},
                    "use_password": {"type": "boolean", "description": "是否使用密码解密", "default": False},
                    "password": {"type": "string", "description": "解密密码（如果use_password为true）"}
                },
                "required": ["encrypted_text"]
            },
        ),
        Tool(
            name="query_arbitration_cases",
            description="查询仲裁案件",
            inputSchema={
                "type": "object",
                "properties": {
                    "status": {"type": "string", "description": "案件状态筛选条件（可选）"},
                    "keyword": {"type": "string", "description": "搜索关键词（可选）"}
                },
                "required": []
            },
        ),
        Tool(
            name="get_available_cases",
            description="获取所有可用的仲裁案件",
            inputSchema={
                "type": "object",
                "properties": {},
                "required": []
            },
        ),
    ]

@server.call_tool()
async def handle_call_tool(name: str, arguments: dict[str, Any] | None) -> list[types.TextContent]:
    """处理工具调用"""
    if arguments is None:
        arguments = {}
    
    if name == "encrypt_string":
        text = arguments.get("text", "")
        use_password = arguments.get("use_password", False)
        password = arguments.get("password", "")
        
        try:
            if use_password and password:
                result = crypto.encrypt_with_password(text, password)
                return [TextContent(type="text", text=f"密码加密结果: {result}")]
            else:
                result = crypto.encrypt_string(text)
                return [TextContent(type="text", text=f"加密结果: {result}")]
        except Exception as e:
            return [TextContent(type="text", text=f"加密失败: {str(e)}")]
    
    elif name == "decrypt_string":
        encrypted_text = arguments.get("encrypted_text", "")
        use_password = arguments.get("use_password", False)
        password = arguments.get("password", "")
        
        try:
            if use_password and password:
                result = crypto.decrypt_with_password(encrypted_text, password)
                return [TextContent(type="text", text=f"密码解密结果: {result}")]
            else:
                result = crypto.decrypt_string(encrypted_text)
                return [TextContent(type="text", text=f"解密结果: {result}")]
        except Exception as e:
            return [TextContent(type="text", text=f"解密失败: {str(e)}")]
    
    elif name == "query_arbitration_cases":
        status = arguments.get("status")
        keyword = arguments.get("keyword")
        
        try:
            if keyword:
                cases = db.search_cases(keyword)
            else:
                cases = db.query_cases(status)
            
            result = json.dumps(cases, ensure_ascii=False, indent=2)
            return [TextContent(type="text", text=f"查询结果:\n{result}")]
        except Exception as e:
            return [TextContent(type="text", text=f"查询失败: {str(e)}")]
    
    elif name == "get_available_cases":
        try:
            cases = db.get_available_cases()
            result = json.dumps(cases, ensure_ascii=False, indent=2)
            return [TextContent(type="text", text=f"可用案件:\n{result}")]
        except Exception as e:
            return [TextContent(type="text", text=f"获取可用案件失败: {str(e)}")]
    
    else:
        raise ValueError(f"未知工具: {name}")

async def main():
    """主函数"""
    # 在stdio上运行服务器
    async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
        await server.run(
            read_stream,
            write_stream,
            server.create_initialization_options()
        )

if __name__ == "__main__":
    asyncio.run(main())
